package org.dingyom.gift.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.dingyom.gift.constants.TypeConstants;
import org.dingyom.gift.domain.LoginUser;
import org.dingyom.gift.domain.Permission;
import org.dingyom.gift.dto.LoginDto;
import org.dingyom.gift.exception.asserts.Assert;
import org.dingyom.gift.mapper.LoginUserMapper;
import org.dingyom.gift.mapper.PermissionMapper;
import org.dingyom.gift.properties.Oauth2ClientDetails;
import org.dingyom.gift.properties.Oauth2ClientDetailsProperties;
import org.dingyom.gift.service.ILoginUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.dingyom.gift.util.AjaxResult;
import org.dingyom.gift.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dingyom
 * @since 2022-10-10
 */
@Service
public class LoginUserServiceImpl extends ServiceImpl<LoginUserMapper, LoginUser> implements ILoginUserService {

    @Autowired
    private LoginUserMapper loginUserMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private Oauth2ClientDetailsProperties oauth2ClientDetailsProperties;
    @Override
    public Long add(LoginUser loginUser) {
        loginUserMapper.insert(loginUser);
        return loginUser.getId();
    }

    @Override
    public AjaxResult account(LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        Oauth2ClientDetails oauth2ClientDetails = oauth2ClientDetailsProperties
                .getOauth2ClientDetails(loginDto.getType());
        String clientId = oauth2ClientDetails.getClientId();
        String clientSecret = oauth2ClientDetails.getClientSecret();
        //空校验 jsr303已完成
        //用户存在校验
        Wrapper<LoginUser> wrapper = new EntityWrapper<LoginUser>().eq("username", username)
                .or().eq("tel", username)
                .or().eq("email", username)
                .andNew().eq("email", loginDto.getType());
        List<LoginUser> loginUsers = loginUserMapper.selectList(wrapper);

        String url = "http://localhost:10030/services/auth/oauth/token?client_id=%s&client_secret=%s&grant_type=password&username=%s&password=%s";

        url = String.format(url, clientId, clientSecret, username, password);

        Map<String, String> result = HttpUtil.sendPost(url);
        String error = result.get("error");
        String errorDescription = result.get("error_description");
        Assert.isEmpty(error,errorDescription);//断言为空 校验了用户是否存在和密码是否正确

        //已经校验完成 相当于登陆已经成功了，将token生成和返回
        String token = result.get("access_token");//token
        String refreshToken = result.get("refresh_token");//刷新token
        LoginUser loginUser = loginUsers.get(0);


        Map<String,Object> resultMap = new HashMap<>();
        //获取用户权限列表
        if (loginDto.getType()== TypeConstants.TYPE_SYSTEM_EMPLOYEE){

            List<Permission> permissions = permissionMapper.selectPermissionByUserId(loginUser.getId());
            List<String> sns = permissions.stream().map(p -> p.getSn()).collect(Collectors.toList());
            resultMap.put("permissions",sns);
        }


        resultMap.put("token", token);
        resultMap.put("refreshToken",refreshToken);
        loginUser.setPassword("******");//密码置空或者这样设置成*
        resultMap.put("loginUser", loginUser);


        return AjaxResult.me().setResultObj(resultMap);
    }
}
